package hostsystem;

import java.io.IOException;
//import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {

		HttpSession session = req.getSession();
        
		
		String account_id = req.getParameter("account_id");
		String password = req.getParameter("password");
		String msg = null;
		String epass=SetMD5.getMD5(password);
		//System.out.println("epass "+epass);
		Connection con = hostdb.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = con.prepareStatement("select * from users where account_id=?");
			ps.setString(1, account_id);
			rs = ps.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		session.setAttribute("islogin", null);
		
		try {
			if (rs.next()) {
				if (rs.getString("password").equals(epass)) {
					// valid login, set session
					session.setAttribute("islogin", true);
					session.setAttribute("signin", null);
					session.setAttribute("accountid", account_id);
					ps.close();
					con.close();
					req.getRequestDispatcher("/main.jsp").forward(req, resp);
				} else {
					// redirect to login page and show password not match
					ps.close();
					con.close();
					msg = "Wrong Password!";
					req.setAttribute("loginsfail",true);
					req.setAttribute("msg", msg);
					req.getRequestDispatcher("/msg.jsp").forward(req, resp);
				}

			} else {
				// user not exists
				ps.close();
				con.close();
				msg = "User not exists!";
				req.setAttribute("loginsfail",true);
				req.setAttribute("msg", msg);
				req.getRequestDispatcher("/msg.jsp").forward(req, resp);
			}
			ps.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.sendRedirect("login.html");
	}
}